package cn.schoolwow.util.module.query.instanceList.flow.filter;

import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import cn.schoolwow.util.domain.query.instance.QueryInstance;
import cn.schoolwow.util.module.query.instanceList.domain.InstanceListQueryOption;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class FilterInstanceByFieldListValueFlow implements BusinessFlow {
    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        InstanceListQueryOption instanceQueryOption = flowContext.checkInstanceData(InstanceListQueryOption.class);
        List<Object> filterInstanceList = (List<Object>) flowContext.getData("filterInstanceList");

        if(null==instanceQueryOption.fieldValueCollectionMap ||instanceQueryOption.fieldValueCollectionMap.isEmpty()){
            return;
        }
        Map<Collection<String>, Collection> collectionMap = instanceQueryOption.fieldValueCollectionMap;
        Set<Collection<String>> keySet = collectionMap.keySet();

        filterInstanceList.removeIf(instance->{
            for(Collection<String> fieldNames:keySet){
                Object fieldValue = null;
                if(fieldNames.size()==1){
                    String fieldName = fieldNames.iterator().next();
                    fieldValue = QueryInstance.newQuery(instance).execute().getSingleFieldValue(fieldName);
                }else{
                    fieldValue = QueryInstance.newQuery(instance).execute().getMultipleFieldValue(fieldNames);
                }
                List expectValueList = (List) collectionMap.get(fieldNames);
                if(!expectValueList.contains(fieldValue)){
                    return true;
                }
            }
            return false;
        });
    }

    @Override
    public String name() {
        return "根据实例字段列表值过滤";
    }

}
